<template>
    <section>
        <!--工具条-->
        <el-row :gutter="20">
            <el-col :lg="14" :md="24">
                <div class="grid-content bg-purple" :style="{backgroundColor:titleColor,position:'relative'}">
                    <div class="dev-title">设备概述</div>
                    <div class="onoffline" :style="{backgroundColor:facility.state==0?'rgba(220, 222, 234, 0.20)':'rgba(108, 227, 89, 0.20)',borderColor:facility.state==0?'#a9a9ae':'#4AC936'}">
                        <span class="onoffline-point" :style="{backgroundColor:facility.state==0?'#a9a9ae':'#4AC936'}"></span>
                        <span :style="{color:facility.state==0?'#a9a9ae':'#4AC936'}">{{facility.stateText}}</span>
                    </div>
                </div>
                <div style="padding:12px 15px;height: 300px;display: flex;" class="col-bg clearfix">
                    <!-- <el-col > -->
                        <div class="device_img"> <img :src="imgUrl?imgUrl:require('../../assets/79761007764060c4e63247c8f2a32ab.png')" /></div>
                        <!-- <el-button class="controlbtn" :type="buttonColor" v-on:click="deviceVisible=true">群控列表</el-button> -->
                        <!-- <el-button class="controlbtn" :type="buttonColor" @click="details">视频列表</el-button>
                        <el-button class="controlbtn" :type="buttonColor" v-if="facility.deviceTemplateId=='380'" @click="goPlay">打开摄像头</el-button>
                        <el-button class="controlbtn" :type="buttonColor" v-if="menubt.indexOf('/topo')>-1" @click="topo">云组态</el-button> -->
                    <!-- </el-col> -->
                    <!-- <el-col > -->
                        <div class="device_p" style="width: 100%;">
                            <div class="name-title">
                                <div class="ng-binding" style="display: flex;align-items: center;">
                                    <!-- <div class="onoffline" :style="{backgroundColor:facility.state==0?'rgba(220, 222, 234, 0.20)':'rgba(108, 227, 89, 0.20)',borderColor:facility.state==0?'#a9a9ae':'#4AC936',position:'relative',top:0,right:0}">
                                        <span class="onoffline-point" :style="{backgroundColor:facility.state==0?'#a9a9ae':'#4AC936'}"></span>
                                        <span :style="{color:facility.state==0?'#a9a9ae':'#4AC936'}">{{facility.stateText}}</span>
                                    </div> -->
                                    <span style="font-size: 20px;margin-left:10px;font-weight:600;">{{facility.name}}  </span>    
                                    <!-- <i @click="nameFormVisible=true"  style="width:24px;height:20px;vertical-align: baseline;" title="编辑" icon="el-icon-edit" circle class="pb-icon icon-edit"></i> -->
                                    <img @click="nameFormVisible=true" src="../../assets/icon/编辑icon@2x.png" style="display: inline-block; width:20px;height:20px;vertical-align: baseline;" />
                                </div>
                                <div class="ng-binding" style="font-size: 19px;color: #B1B1B1;">
                                    激活时间：{{ facility.updateTime }}
                                </div>
                                <!-- <div class="onoffline" :style="{backgroundColor:facility.state==0?'rgba(220, 222, 234, 0.20)':'rgba(108, 227, 89, 0.20)',borderColor:facility.state==0?'#a9a9ae':'#4AC936'}">
                                    <span class="onoffline-point" :style="{backgroundColor:facility.state==0?'#a9a9ae':'#4AC936'}"></span>
                                    <span :style="{color:facility.state==0?'#a9a9ae':'#4AC936'}">{{facility.stateText}}</span>
                                </div> -->
                            </div>
                            <div class="device-msg" style="display: flex;">
                                <div class="device-msg-detail">
                                    <img class="device-msg-image" src="../../assets/icon/devicetype.png" alt="" /> 
                                    <div style="margin-left:13px;">
                                        <div class="device-msg-title">设备类型</div>
                                        <div class="device-msg-name">{{facility.deviceTypeName}}</div>
                                    </div>
                                </div>
                                <div class="device-msg-detail">
                                    <img class="device-msg-image" src="../../assets/icon/devicemode.png" alt="" /> 
                                    <div style="margin-left:13px;">
                                        <div class="device-msg-title">设备模板</div>
                                        <div class="device-msg-name">{{facility.deviceTemplateName}}</div>
                                    </div>
                                </div>
                                <div class="device-msg-detail">
                                    <img class="device-msg-image" src="../../assets/icon/xinhao.png" alt="" /> 
                                    <div style="margin-left:13px;">
                                        <div class="device-msg-title">信号强度</div>
                                        <div class="device-msg-name">
                                            <span :class="[wife>=1? 'bg-greens':'bg-gray']"></span>
                                            <span :class="[wife>=2? 'bg-greens':'bg-gray']"></span>
                                            <span :class="[wife>=3? 'bg-greens':'bg-gray']"></span>
                                            <span :class="[wife>=4? 'bg-greens':'bg-gray']"></span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div style="display:flex;justify-content:space-between;">
                                <div class="device-msg device-msg-fontsize" style="text-align: center;padding: 14px 16px;width:46%;margin:13px 0 0;">
                                    <div class="device-msg-bottomline flex justify-between">
                                        <div>
                                            <img class="device-msg-icon" src="../../assets/icon/激活状态icon@2x.png" alt="" /> 
                                            <span style="margin-left:10px;">激活状态</span>
                                        </div>
                                        <div class="devicemsg-value">
                                            未激活
                                        </div>
                                    </div>
                                    <div class="flex justify-between" style="margin-top:20px;">
                                        <div>
                                            <img class="device-msg-icon" src="../../assets/icon/激活时间icon@2x.png" alt="" /> 
                                            <span style="margin-left:10px;">设备id</span>
                                        </div>
                                        <div class="devicemsg-value">
                                            {{facility.deviceId}}
                                        </div>
                                    </div>
                                </div>
                                <div class="device-msg device-msg-fontsize" style="text-align: center;padding: 14px 16px;width:46%;margin:13px 0 0;">
                                    <div class="device-msg-bottomline flex justify-between">
                                        <div>
                                            <img class="device-msg-icon" src="../../assets/icon/SNicon@2x.png" alt="" /> 
                                            <span style="margin-left:10px;">SN</span>
                                        </div>
                                        <div class="devicemsg-value">
                                            {{facility.deviceSn}}
                                        </div>
                                    </div>
                                    <div class="flex justify-between" style="margin-top:20px;">
                                        <div>
                                            <img class="device-msg-icon" src="../../assets/icon/型号icon@2x.png" alt="" /> 
                                            <span style="margin-left:10px;">型号</span>
                                        </div>
                                        <div class="devicemsg-value">
                                            {{facility.deviceModelName}}
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                        </div>
                    <!-- </el-col> -->
                </div>
            </el-col>
            <el-col :lg="10" :md="24">
                <div class="grid-content bg-purple" :style="{backgroundColor:titleColor}">

                    <div class="dev-title">设备地图</div>
                </div>
                <div style="padding:12px 15px" class="col-bg clearfix">
                    <div id="allmap" ref="allmap"></div>
                </div>
            </el-col>
        </el-row>
            <el-tabs type="border-card" @tab-click="changeTab">
                <!-- <el-tab-pane label="基本信息">设备ID，SN，名称，图片，设备类型，型号，网络状态，激活状态，告警状态，创建时间</el-tab-pane> -->
                <el-tab-pane label="数据点信息">
                    <!-- <span slot="label"><i class="el-icon-date"></i> 数据点列表</span> -->
                
                    <el-col :span="24" class=" clearfix">
                        <div class=" pb-top  clearfix">
                            <el-col :span="24" class="toolbar" style="padding:10px 10px 0 10px">
                                <el-form :inline="true" :model="filters">
                                    <el-form-item>
                                        <el-input v-model="selectlist.name" @change="search" placeholder="数据点名称"></el-input>
                                    </el-form-item>
                                    <el-form-item>
                                        <el-input v-model="selectlist.register" @change="search" placeholder="数据点地址"></el-input>
                                    </el-form-item>
                                    <el-form-item>

                                        <el-select v-model="selectlist.writeRead" placeholder="读写" @change="search" size="mini">

                                            <el-option label="全部" key='' value=''></el-option>
                                            <el-option key="0" label="读" value="0"></el-option>
                                            <el-option key="1" label="读写" value="1"></el-option>
                                            <!-- <el-option key="2" label="读写" value="2"></el-option> -->
                                        
                                        </el-select>
                                        <el-select v-model="selectlist.dataType" @change="search" placeholder="数据类型"
                                            size="mini">

                                            <el-option label="全部" key='' value=''></el-option>
                                            <el-option key="0" label="数值型" value="0"></el-option>
                                            <el-option key="1" label="开关型" value="1"></el-option>
                                            <el-option key="2" label="字符型" value="2"></el-option>
                                            
                                        </el-select>
                                        <el-select v-model="selectlist.unitId" @change="search"  placeholder="数据单位" size="mini">
                                            <el-option label="全部" key='' value=''></el-option>
                                            <el-option v-for="item in unitList" :label="item.name+' - '+item.value" :value="item.id"></el-option>
                                        </el-select>

                                    </el-form-item>
                                    <el-form-item>
                                        <el-button :type="buttonColor" v-on:click="search">查询</el-button>
                                    </el-form-item>
                                    <!-- <el-form-item>
                                        <el-button :type="buttonColor" v-on:click="deviceVisible=true">设备群控</el-button>
                                    </el-form-item> -->
                                    <!-- <el-form-item>
                                    <el-checkbox v-model="checked">是否群控(记得先选上设备)</el-checkbox>
                                    </el-form-item> -->
                                    <br />
                                    <el-form-item>
                                        数据点总数:{{hande_device_list.length}} 告警点数量：{{AlarmNum}}
                                    </el-form-item>
                                </el-form>
                            </el-col>

                            <!--列表-->



                            <!--工具条-->

                        </div>
                        <div class="grid-content bg-purple" :style="{backgroundColor:titleColor}">
                            <div class="dev-title">数据点概况</div>
                        </div>

                        <div class="col-bg clearfix">
                            <el-row :gutter="10">
                                <el-col :lg="12" :md="24" v-for="(item,index) in hande_device_list" style="padding: 5px;">
                                    <div style="background: #FAFBFD;padding: 20px 10px;border-radius: 5px;border: 1px solid #E7EBEE;display: flex;align-items: center;" class="clearfix">
                                        <el-col :xs="12" :sm="8">
                                            <div class="devicepoint-title">{{item.name}}</div>
                                            <!-- <div class="devicepoint-content">数据点地址:{{item.register}}</div> -->
                                            <div class="devicepoint-content">数据点地址:{{item.register}}</div>
                                        </el-col>
                                        <el-col :xs="12" :sm="4">
                                            <div class="devicepoint-title">从机名称</div>
                                            <div class="devicepoint-content">{{item.deviceSlaveName}}</div>
                                        </el-col>
                                        <el-col :xs="12" :sm="2" style="text-align: left;">
                                            <div class="devicepoint-title">状态</div>
                                            <div v-if="facility.state==1">
                                                <span v-if="item.communicateState==0" class="pb-colorbg bg-green"
                                                    title="正常">正常</span>
                                                <span v-if="item.communicateState==1" class="pb-colorbg bg-red"
                                                    title="故障">故障</span>
                                                <span v-if="item.communicateState==null" class="pb-colorbg bg-grays"
                                                    title="未知">未知</span>
                                            </div>
                                            <div v-else>
                                                <span class="pb-colorbg bg-grays" title="离线">离线</span>
                                            </div>
                                        </el-col>
                                        <el-col :xs="12" :sm="3">
                                            <div class="devicepoint-title">{{item.updateTime.split(' ')[0]}}</div>
                                            <div class="devicepoint-content">{{item.updateTime.split(' ')[1]}}</div>
                                        </el-col>

                                        <el-col :xs="12" :sm="3" style="min-heigth:20px">
                                            <div v-if="item.dataType==1  ">
                                                <el-tooltip v-if="item.registerVal==0||item.registerVal==1" :content="'开关'">
                                                    <el-switch @change="scade(index, item)" v-model="item.registerVal"
                                                        :disabled="item.writeRead==0||menubt.indexOf('/device/cmd')==-1"
                                                        active-value="1" inactive-value="0">
                                                    </el-switch>

                                                </el-tooltip>
                                                <div v-else>无效</div>
                                            </div>
                                            <span v-if="item.dataType!=1">
                                                <div class="devicepoint-title">当前值：</div>
                                                <div style="max-width: 100px;overflow: hidden;">
                                                    <span class="devicepoint-content" style="max-height: 20px;">{{item.registerVal}}</span>
                                                    <span class="devicepoint-content" v-if="item.unit">({{item.unit}})</span>
                                                </div>
                                            </span>
                                        </el-col>
                                        <!-- <el-col :xs="12" :sm="2" style="min-height:40px;">
                                            <img v-if="item.picturePath" :title="item.deviceRecipePictureGroupText"
                                                :src="item.picturePath" style="width: 40px;height: 40px;">
                                            <span v-else>{{item.pictureRemark}}</span>
                                        </el-col> -->
                                        <el-col :xs="12" :sm="3">
                                            <span v-if="item.writeRead==1 && item.dataType!=1&&menubt.indexOf('/device/cmd')>-1">
                                                <i title="写数据点值" @click="fromedit(index,item)" type="warning" class="pb-icon icon-bianji"></i>
                                            </span>
                                            <span v-else>
                                                <i title="禁止使用" type="warning" class="pb-icon icon-bianjino"></i>
                                            </span>
                                            <i v-if="menubt.indexOf('/devices/history')>-1" @click="handlehisty(index, item)" title="历史查询" circle class="pb-icon icon-lishi"></i>
                                            <i v-if="menubt.indexOf('/device/cmd')>-1" @click="scade1(index, item)" circle title="主动采集" class="pb-icon icon-caiji"></i>
                                        </el-col>
                                    </div>
                                </el-col>
                                <!-- <el-col :span="24" class="toolbar">
                                
                                    <el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="10"
                                        :total="total" style="float:right;">
                                    </el-pagination>
                                </el-col> -->
                            </el-row>
                        </div>
                    </el-col>
                </el-tab-pane>
                <el-tab-pane label="版本信息">
                    <!-- <slave></slave> -->
                    <div style="font-size: 21px;">
                        <!-- <div>
                            状态：{{upgradeData.state==1? '在线':'离线'}}
                        </div> -->
                        <div class="version-msg">
                            <span class="version-label">软件版本号：</span>
                            <span class="version-value">{{upgradeData.softCode}}</span>
                        </div>
                        <div class="version-msg">
                            <span class="version-label">软件版本：</span>
                            <span class="version-value">{{upgradeData.softVersion}}</span>
                        </div>
                        <!-- <div>
                            软件编码：{{upgradeData.softCode}}
                        </div> -->
                        <div class="version-msg">
                            <span class="version-label">硬件版本：</span>
                            <span class="version-value">{{upgradeData.hardwareVersion}}</span>
                        </div>
                        <div class="version-msg">
                            <span class="version-label">参数版本：</span>
                            <span class="version-value">{{upgradeData.paramsVersion}}</span>
                        </div>
                        <div class="version-msg">
                            <span class="version-label">ICCID：</span>
                            <span class="version-value">{{upgradeData.iccid}}</span>
                        </div>
                        <!-- <div>
                            更新时间：{{upgradeData.updateTime}}
                        </div> -->
                    </div>
                </el-tab-pane>
                <el-tab-pane label="告警数据">
                    <alarm-history :isComponent="true"></alarm-history>
                </el-tab-pane>
                <el-tab-pane label="操作日志">
                    <user-event v-if="facility.deviceId" :isComponent="true" :componentDeviceId="facility.deviceId"></user-event>
                </el-tab-pane>
                <el-tab-pane label="设备转移">
                    <!-- <div>当前组织：xxx组织</div> -->
                    <el-select style="margin-top: 10px;" v-model="toCompanyId" filterable placeholder="请选择转到的组织">             
                        <el-option v-for="(item,index) in userlist"  :label="item.name" :value="item.companyId"></el-option>
                    </el-select>
                    <div style="margin-top: 10px;">
                        <el-button :type="buttonColor" @click.native="onSubmit" :loading="editLoading">提交</el-button>
                    </div>
                </el-tab-pane>
                <el-tab-pane label="历史数据">
                    <devices-history  v-if="facility.deviceId" :isComponent="true" :componentDeviceId="facility.deviceId"></devices-history>
                </el-tab-pane>
        </el-tabs>
        

        <!--列表-->
        <!--编辑界面-->
        <el-dialog title="编辑" v-show="editFormVisible" v-model="editFormVisible" :custom-class="dialogTitleColor" @close="editFormVisible=false">
            <div slot="footer" style="text-align: left; ">
                <el-form  label-width="100px">
                    <el-form-item label="数据点值" prop="name">
                        <el-input v-model="value2"  auto-complete="off"></el-input>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer" style="text-align:right;">
                    <el-button @click.native="editFormVisible = false">取消</el-button>
                    <el-button :type="buttonColor" @click.native="editSubmit" v-loading="listLoading">提交</el-button>
                </div>
            </div>
        </el-dialog>
         <el-dialog title="设备名称" v-show="nameFormVisible" v-model="nameFormVisible" :custom-class="dialogTitleColor" @close="nameFormVisible=false">
            <div slot="footer" style="text-align: left; ">
                <el-form ref="device" :rules="editNameRules" :model="device" label-width="100px" >
                    <el-form-item label="设备名称" prop="name">
                        <el-input v-model="device.name"  auto-complete="off"></el-input>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer" style="text-align:right;">
                    <el-button @click.native="nameFormVisible = false">取消</el-button>
                    <el-button :type="buttonColor" @click.native="nameSb" v-loading="listLoading">提交</el-button>
                </div>
            </div>
        </el-dialog>
          <!--设备群控-->
        <el-dialog title="设备群控" v-show="deviceVisible" v-model="deviceVisible" :custom-class="dialogTitleColor" @close="deviceVisible=false">
            <div slot="footer"  class="clearfix" style="text-align: left; ">
                <el-col :span="8" v-loading='listLoading'>
                    <el-tree @node-click="getlists" :data="query" :props="defaultProps" node-key="id" default-expand-all :expand-on-click-node="false" :render-content="renderContent"></el-tree>
                </el-col>
                <el-col :span="16">
                  <el-transfer :titles="['可选', '已选']" :button-texts="['到左边', '到右边']" v-model="binddata" :data="datalist" style="padding-left:30px;padding-bottom:20px;"></el-transfer>
                </el-col>
                <div slot="footer" class="dialog-footer" style="text-align:right;">
                    <el-button @click.native="deviceVisible= false" >确定</el-button>
                    <!-- <el-button :type="buttonColor" @click.native="deviceSb" >提交</el-button> -->
                </div>
            </div>
        </el-dialog>
    </section>
</template>
<script>
    import Slave from '@/views/device/upgrade/slave'
    import AlarmHistory from '@/views/alarms/history'
    import UserEvent from '@/views/devices/operationLogs'
    import DevicesHistory from '@/views/devices/history'
    import {
        device_group_query,
        device_company_group_query ,
        device_get,
        device_recipe_body_list,
        device_cmd,
        device_recipe_picture_query_body,
        device_getDeviceAlarmNum,
        unit_query,
        video_query,
        device_put,
        device_attr_query,
        user_querycompany,
        device_change_user
    } from '../../api/api';
    //import NProgress from 'nprogress'
    export default {
    //     renderContent(h, { node, data, store }) {
    
    // return (
    //     <span style="width:100%;">
    //       <span>
    //         <span>{node.label}</span>
    //       </span>
    //     </span>
    //   );
      
      
    // },
    components:{
        Slave,
        AlarmHistory,
        UserEvent,
        DevicesHistory
    },
        data() {
            return {
                toCompanyId:"",
                device:{
                    name:''
                },
                editNameRules:{
                    name: [{
                        required: true,
                        message: '请填写设备名称',
                        trigger: 'blur'
                    }, {
                        min: 1,
                        max: 40,
                        message: '长度在 1 到 40 个字符',
                        trigger: 'blur'
                    }],
                },
                checked:false,
                videolist:'',//监控列表
                datalist: [], //数据源
                binddata: [], //绑定的数据,
                bindlist: [], //过滤用的数据源
                // deviceQuery: [],
                deviceIdList:[],
                unitList:'',
                deviceGroupId:'',
                querys:'',
                query:'',
                 defaultProps: {
                    children: "childrens",
                    label: "name"
                },
                index:'',
                checkClick: false,
                total: '',
                wife: '',
                imgUrl: '',
                editForm: '',
                editFormVisible: false,
                deviceVisible: false,//设备群控弹窗
                nameFormVisible:false,//设备名修改弹窗
                value2: '',
                device_list: '',
                device_lists: '',
                hande_device_list: [],
                filters: {
                    name: ''
                },
                loading: false,
                users: [],
                facility: {},
                selectlist: {
                    name: '',
                    writeRead: '',
                    dataType: '',
                    register: '',
                    unitId:''
                },
                t: '',
                page: 1,
                AlarmNum: '',
                listLoading:false,
                upgradeData:{},
                userlist:[]
            }
        },
        computed:{
            buttonColor(){
                return this.$store.state.buttonColor
            },
            titleColor(){
                return this.$store.state.titleColor
            },
            dialogTitleColor(){
                return this.$store.state.dialogTitleColor
            },
        },
        methods: {
            onSubmit(){
                if(!this.toCompanyId){
                    this.$message({
                        message: '请选择需要转移到的组织',
                        type: 'warning'
                    });
                    return false
                }
                this.$confirm('确认提交吗？', '提示', {}).then(() => {
                    let para = {
                        deviceId: sessionStorage.getItem('facility_details')? sessionStorage.getItem('facility_details'):localStorage.getItem('facility_details'),
                        toCompanyId: this.toCompanyId
                    }
                    console.log(para)
                    device_change_user(para).then((res) => {
                        if (res.code == 0) {
                            this.editLoading = false;
                            this.$message({
                                message: '提交成功',
                                type: 'success'
                            });
                            
                            this.userget();
                        } else if(res.code == 600){
                            this.$message({
                                message: '设备已在该组织内',
                                type: 'warning'
                            });
                        }else{
                            this.begCode(res.code, res.message);
                        }
                    });
                });
            },
            //获取分组列表
            getCompany(){
                let para = {
                    pageNo: 1,
                    pageSize: 9999,
                    type: 1
                }
                user_querycompany(para).then((res) => {
                    this.begCode(res.code, res.message);
                    this.userlist = res.data.list;
                });
            },
            //切换标签触发事件
            changeTab(e){
                // console.log(e.index)
                let curIndex = e.index
                if(curIndex==1){
                    this.getDeviceUpgrade()
                }
            },
            //查询设备升级列表
            getDeviceUpgrade(){
                // console.log(this.facility)
                let para = {
                    deviceSn: this.facility.deviceSn
                }
                device_attr_query(para).then(res=>{
                    this.upgradeData = res.data.list[0]
                    console.log(this.upgradeData)
                })
            },
            renderContent(h, { node, data, store }) {
                return (
                    <span style="width:100%;">
                    <span>
                        <span>{node.label}</span>
                    </span>
                    </span>
                );
            },
            getlists(s){
                this.deviceGroupId = s.id;
                this.getlist();
            },
        //名称修改
        nameSb(){
            this.$refs.device.validate((valid) => {
            if (valid) {
                this.facility.name=this.device.name;

                let para = this.facility;
                    this.listLoading = true;

                    device_put(para).then(res => {
                        this.begCode(res.code, res.message);
                        this.nameFormVisible = false;
                        this.$message({
                            message: '修改成功',
                            type: 'warning'
                        });
                        this.listLoading = false;
                
                    });
            }
            });
        
        },
     deviceSb() {
      console.log(this.binddata);
      this.deviceIdList=this.binddata;
      console.log(this.deviceGroupId);
     
    
    },
     getlist() {

      let para = {
        deviceGroupId: this.deviceGroupId,
        deviceTemplateId: this.facility.deviceTemplateId,
          pageNo: 1,
        pageSize: 1000,
      };
      this.listLoading = true;
      //NProgress.start();
      device_company_group_query(para).then(res => {
        this.begCode(res.code, res.message);
        this.deviceQuery = res.data.list;
        
        if(this.datalist.length == 0){
            for (let i in res.data.list) {
            this.datalist.push({
                key: res.data.list[i].deviceId,
                label: res.data.list[i].name
            });
            }
        }else{

            for(let i=0; i< this.datalist.length; i++){
                for(let k=0; k<this.deviceQuery.length;k++){
                    if(this.datalist[i].key === this.deviceQuery[k].deviceId){
                        this.deviceQuery.splice(k,1)
                    }
                }
            }

            if(this.deviceQuery.length >0){
                for(let i in this.deviceQuery){
                    this.bindlist.push({
                        key: this.deviceQuery[i].deviceId,
                        label: this.deviceQuery[i].name,
                    })
                }

                for(let j=0; j<this.bindlist.length; j++){
                    this.datalist = this.datalist.concat(this.bindlist[j])
                }
            }  
            console.log(this.datalist)
        }
        // console.log(this.datalist)
        
        // }
        // this.binddata = [];
        // for (let i in this.deviceQuery) {
        //   this.binddata.push(this.deviceQuery[i].deviceId);
        // }
        // this.datalist = [];
        // console.log(res.data.list)
        // for (let i in res.data.list) {
        //   this.datalist.push({
        //     key: res.data.list[i].deviceId,
        //     label: res.data.list[i].name
        //   });
        // }
        // console.log(this.datalist)
        this.listLoading = false;
        //NProgress.done();
      });
    },
            search() {
                this.hande_device_list = [];
                for (let i in this.device_list) {
                    // if(this.selectlist.name==res.data.)
                    if (this.device_list[i].name.indexOf(this.selectlist.name) >= 0) {
                        if (this.device_list[i].register.indexOf(this.selectlist.register) >= 0) {
                            if (this.device_list[i].dataType == this.selectlist.dataType || this.selectlist.dataType ==
                                '') {
                                if (this.device_list[i].writeRead == this.selectlist.writeRead || this.selectlist
                                    .writeRead == '') {
                                        if(this.device_list[i].unitType == this.selectlist.unitId || this.selectlist.unitId == ''){
                                            this.hande_device_list.push(this.device_list[i]);
                                        }
                                }
                            }
                        }
                    }

                }

                this.total = this.hande_device_list.length;
                console.log(this.hande_device_list)
                // this.total = this.device_list.length;

                // this.selectget();
            },

            
            handleCurrentChange(val) {
                this.page = val;
            },
            handleSave2(s) {
                let para = {
                    deviceId: sessionStorage.getItem('facility_details')
                };
                console.log(s);
                if (s.deviceId == sessionStorage.getItem('facility_details')) {
                device_get(para).then((res) => {
                     this.begCode(res.code,res.message);
                    this.wife = this.formatwife(res.data.deviceAttr)
                    this.facility = res.data;
                    //NProgress.done();
                });
                }
            },
            handleSave1(s) {
                let _this = this;
                console.log(s.deviceId)
                console.log(sessionStorage.getItem('facility_details'))
                if (s.deviceId == sessionStorage.getItem('facility_details')) {
                    let para = {
                        deviceId: sessionStorage.getItem('facility_details')
                    };
                    console.log(this.checkClick)
                    if (this.checkClick == true) {

                        return false;
                    }
                    this.checkClick = true;

                    setTimeout(function () {
                        console.log(_this.checkClick)
                        _this.checkClick = false;
                    }, 3000);
                    this.getbodylist();
                    device_get(para).then((res) => {
                        this.begCode(res.code,res.message);
                        this.wife = this.formatwife(res.data.deviceAttr)
                        this.facility = res.data;

                        //NProgress.done();
                    });
                    device_getDeviceAlarmNum(para).then((res) => {
                        //  this.begCode(res.code,res.message);
                        this.AlarmNum = JSON.parse(res.data).alarmNum;
                        console.log(JSON.parse(res.data).alarmNum)

                        //NProgress.done();
                    });

                }
            },
            selectget() {
                let tosize1 = 10 * (this.page - 1)
                let tosize2 = 10 * this.page;
                if (this.device_list) {

                    this.hande_device_list = this.device_list.slice(tosize1, tosize2);
                    console.log(this.hande_device_list)

                }

            },
            chekedList(){
                
                if(this.checked){
                    
                this.deviceIdList=this.binddata;
                    // this.deviceIdList.push(sessionStorage.getItem('facility_details'));
                }else{
                    this.deviceIdList=[sessionStorage.getItem('facility_details')];
                }
                console.log(this.deviceIdList)
            },
            scade1(index, row) {
               this.chekedList();
                let para = {
                    code: 'getRegisterData',
                    deviceIdList: this.deviceIdList,
                    attrs: {
                        deviceSlaveSn: row.slaveSn,
                        registerFirstAddr: row.register,
                        count: 1
                    }
                };
                console.log(para)
                this.loading = true;
                //NProgress.start();
                device_cmd(para).then((res) => {
                     this.begCode(res.code,res.message);
                    this.$message({
                        message: '下发命令成功',
                        type: 'success'
                    });
                    this.getbodylist();
                    //NProgress.done();
                });
            },
            scade(index, row) {
                
               this.chekedList();
                // this.$confirm('确认更换吗？', '提示', {}).then(() => {
                let para = {
                    code: 'writeRegisterData',
                    deviceIdList: this.deviceIdList,
                    attrs: {
                        deviceSlaveSn: row.slaveSn,
                        register: row.register,
                        registerVal: row.registerVal,
                        deviceType: 1
                    }
                };
                this.loading = true;
                //NProgress.start();
                device_cmd(para).then((res) => {
                     this.begCode(res.code,res.message);
                    if(res.code==0){
                        this.$message({
                            message: '下发命令成功',
                            type: 'success'
                        });
                    }
                    clearInterval(this.t)
                    this.t = setInterval(() => {
                let para = {
                    deviceId: sessionStorage.getItem('facility_details')? sessionStorage.getItem('facility_details'):localStorage.getItem('facility_details')
                };
                this.getbodylist();
                device_get(para).then((res) => {
                     this.begCode(res.code,res.message);
                    this.wife = this.formatwife(res.data.deviceAttr)
                    this.facility = res.data;

                    //NProgress.done();
                });
                device_getDeviceAlarmNum(para).then((res) => {
                    //  this.begCode(res.code,res.message);
                    this.AlarmNum = JSON.parse(res.data).alarmNum;
                    console.log(JSON.parse(res.data).alarmNum)

                    //NProgress.done();
                });
            }, 10000)
                    // this.getbodylist();
                    //NProgress.done();
                });
                // });
            },
            fromedit(index, row) {
                if (this.menubt.indexOf('/device/cmd') == -1) {
                    this.$message({
                        message: '您没有下发命令的权限',
                        type: 'warning'
                    });
                    return false;
                }
                this.index=index;
                this.editFormVisible = true;
                this.editForm = row;
            },

            signToUnsign(num) { //有符号转无符号  -1 --> 65535
                if (num < 0) {
                    //		var a=~0xffff;
                    num = num & 0xffff;
                }
                console.log(num)
                return num;
            },

            editSubmit() {

                console.log(this.editForm)
                this.$confirm('确认提交吗？', '提示', {}).then(() => {
                    if (this.value2) {
                            // if (this.editForm.decimalAccuracy) {
                                
                            //     this.editForm.registerVal = parseFloat(this.value2 / Math.pow(10,
                            //         this.editForm.decimalAccuracy).toPrecision(12));


                            //     // if (this.editForm.decimalAccuracy == 1) {
                            //     //     this.editForm.registerVal = parseInt(this.value2).toFixed(1)
                            //     // }
                            // }else
                            {
                                this.editForm.registerVal=this.value2;
                            }
                        }
                    this.hande_device_list[this.index].registerVal=this.editForm.registerVal;
                    if(this.value2<0){
                        this.value2=this.signToUnsign(this.value2);
                    }
                
               this.chekedList();
                    let para = {
                        code: 'writeRegisterData',
                        deviceIdList: this.deviceIdList,
                        attrs: {
                            deviceSlaveSn: this.editForm.slaveSn,
                            register: this.editForm.register,
                            registerVal: this.value2
                        }
                    };
                    this.loading = true;
                    
                    //NProgress.start();
                    device_cmd(para).then((res) => {
                         this.begCode(res.code,res.message);
                        this.loading = true;
                        if(res.code==0){
                        this.$message({
                            message: '下发命令成功',
                            type: 'success'
                        });
                        clearInterval(this.t)
                    this.t = setInterval(() => {
                let para = {
                    deviceId: sessionStorage.getItem('facility_details')? sessionStorage.getItem('facility_details'):localStorage.getItem('facility_details')
                };
                this.getbodylist();
                device_get(para).then((res) => {
                     this.begCode(res.code,res.message);
                    this.wife = this.formatwife(res.data.deviceAttr)
                    this.facility = res.data;
                     
                  

                    //NProgress.done();
                });
                device_getDeviceAlarmNum(para).then((res) => {
                    //  this.begCode(res.code,res.message);
                    this.AlarmNum = JSON.parse(res.data).alarmNum;
                    console.log(JSON.parse(res.data).alarmNum)

                    //NProgress.done();
                });
            }, 10000)
                    }
                        this.editFormVisible = false;
                        //NProgress.done();

                        this.value2 = '';
                    });
                });
            },
            //            tableHeaderColor({
            //     row,
            //     column,
            //     rowIndex,
            //     columnIndex
            // }) {
            //     if (rowIndex === 0) {
            //         return 'background-color: #eee;font-weight: 500;'
            //     }
            // },
            //性别显示转换
            handlehisty: function (index, row) {
                console.log(row)
                sessionStorage.setItem('pointid', row.slaveSn+'~'+row.register+'~'+row.deviceSlaveName);
                sessionStorage.setItem('pointslaveSn', row.slaveSn);
                sessionStorage.setItem('pointname', this.facility.name);
                sessionStorage.setItem('deviceDataRecipeId', row.deviceDataRecipeId);
                this.$router.push({
                    path: "/devices/history"
                });
            },
            formatSex: function (row, column) {
                return row.sex == 1 ? '男' : row.sex == 0 ? '女' : '未知';
            },
            formatwife(row) {
                // if (row) {
                //     return row.signalIntensity == 0 ? '很弱' : row.signalIntensity == 1 ? '弱' : row.signalIntensity == 2 ?
                //         '一般' : row.signalIntensity ==
                //         3 ? '普通' : row.signalIntensity == 4 ? '强' : row.signalIntensity == 5 ? '很强' : ' 未知';
                // } else {
                //     return '未知';
                // }
                if (row) {
                    return row.signalIntensity;
                } else {
                    return 0;
                }


            },
            map1() {
                let map = new BMap.Map(this.$refs.allmap); // 创建Map实例
                // map.centerAndZoom(new BMap.Point(116.404, 39.915), 5);
                map.enableScrollWheelZoom();
                map.centerAndZoom(new BMap.Point(116.404, 39.915), 11); // 初始化地图,设置中心点坐标和地图级别
                map.addControl(
                    new BMap.MapTypeControl({
                        //添加地图类型控件
                        mapTypes: [BMAP_NORMAL_MAP, BMAP_HYBRID_MAP]
                    })
                );

                // var map = new BMap.Map("container");
                var point = new BMap.Point(this.facility.deviceLocation.longitude, this.facility.deviceLocation
                    .latitude);
                    var mapStyle = {
          features: ["road", "building", "water", "land"], //隐藏地图上的"poi",
        //   style: "midnight",
        };
        map.setMapStyle(mapStyle);
                map.centerAndZoom(point, 15);
                var marker = new BMap.Marker(point); // 创建标注    
                map.addOverlay(marker);
                var opts = {
                    width: 200, // 信息窗口宽度
                    height: 100, // 信息窗口高度
                    title: "地址信息", // 信息窗口标题
                    enableMessage: true, //设置允许信息窗发送短息
                    message:`<div>地址：${this.facility.deviceLocation.address}~</div><div>更新时间：${this.facility.deviceLocation.updateTime}</div>` 
                }
                var infoWindow = new BMap.InfoWindow(opts.message, opts); // 创建信息窗口对象    
                map.openInfoWindow(infoWindow, map.getCenter()); // 打开信息窗口
                map.addOverlay(marker); // 将标注添加到地图中

                // var infoWindow = new BMap.InfoWindow("地址:" + this.facility.deviceLocation.address, opts); // 创建信息窗口对象 
                marker.addEventListener("click", function () {
                    map.openInfoWindow(infoWindow, point); //开启信息窗口

                });

                // map.setCurrentCity("北京"); // 设置地图显示的城市 此项是必须设置的
                // map.enableScrollWheelZoom(true); //开启鼠标滚轮缩放

            },
            //获取用户列表
            getUser: function () {

                let para = {
                    deviceId: sessionStorage.getItem('facility_details')? sessionStorage.getItem('facility_details'):localStorage.getItem('facility_details')
                };
                this.loading = true;
                //NProgress.start();
                device_get(para).then((res) => {
                    console.log(res);
                    // res.code=403;
                     this.begCode(res.code,res.message);
                    if (res.code == 0) {
                        this.users = res.data.deviceSlaveList;
                        
                        this.facility = res.data;

                    this.getVideoList()
                        
                    this.device.name=this.facility.name;
                        let num = this.wgs84togcj02(this.facility.deviceLocation
                            .longitude, this.facility.deviceLocation
                            .latitude);
                            
                        console.log(num)
                        num = this.gcj02tobd09(num[0], num[1]);
                        this.facility.deviceLocation.longitude = num[0];
                        this.facility.deviceLocation.latitude = num[1]
                        this.wife = this.formatwife(res.data.deviceAttr);
                        this.loading = false;
                        if (res.data.devicePictureList.length>0) {

                            this.imgUrl = res.data.devicePictureList[0].path;
                        } else {
                            // this.imgUrl = '../../assets/img/wifi1.png';
                        }
                        this.map1()
                    }

                    //NProgress.done();
                });
                device_getDeviceAlarmNum(para).then((res) => {
                    //  this.begCode(res.code,res.message);
                    this.AlarmNum = JSON.parse(res.data).alarmNum;

                    //NProgress.done();
                });
                this.getbodylist()


            },
            getbodylist() {

                let para = {
                    deviceId: sessionStorage.getItem('facility_details')? sessionStorage.getItem('facility_details'):localStorage.getItem('facility_details')
                };
                device_recipe_body_list(para).then((res) => {
                     this.begCode(res.code,res.message);

                    for (let i in res.data) {


                        let para1 = {
                            deviceRecipePictureGroupId: res.data[i].deviceRecipePictureGroupId
                        };

                        if (res.data[i].registerVal) {
                            // if (res.data[i].decimalAccuracy) {
                            //     res.data[i].registerVal = parseFloat(res.data[i].registerVal / Math.pow(10,
                            //         res.data[i].decimalAccuracy).toPrecision(12));


                            //     if (res.data[i].decimalAccuracy == 1) {
                            //         res.data[i].registerVal = res.data[i].registerVal.toFixed(1)
                            //     }
                            // }
                        }

                        // this.devide_list[i].registerVal=this.devide_list[i].registerVal/


                    }
                    let ti = setTimeout(() => {

                        // this.updatelist();
                        // this.device_list = res.data;
                        this.device_list = res.data;
                        this.search()

                        return false;
                        

                    }, 300);
                    // this.loading = false;
                    //NProgress.done();
                    
                });
            },
            getrecursion(data) {
                for (var i in data) {
                    this.querys.push(data[i]);
                    OUT:
                    if (!data[i].childrens) {
                    break OUT;
                    } else {
                    this.getrecursion(data[i].childrens);
                    }
                }
                        
                },
            details(){
                sessionStorage.setItem('video_detail',this.facility.deviceId)
                this.$router.push({
                    path: '/devices/videoList'
                })
            },
               topo(){
                 
                 window.open("/configurat/spa/?deviceId="+this.facility.deviceId+"&token="+JSON.parse(localStorage.getItem("key"))+"&id="+this.facility.deviceTemplateId+'#/fullscreen',"_blank");  
                return false;
            
            },
            goPlay() {
                let token = localStorage.getItem("key");
                console.log(this.videolist)
                window.open(
                    "/ys_camera/player/ui-voice.html?videoSn=" +
                    this.videolist.videoSn +
                    "&key=" +
                    token +
                    "",
                    "_blank"
                );
            },
            getVideoList(){
                let para = {
                    pageNo: 1,
                    pageSize: 1000,
                    deviceId: this.facility.deviceId
                };
                video_query(para).then(res => {
                    console.log(res)
                    this.videolist = res.data.list[0];
                });
            }
        },
        mounted() {
              let para1 = {
                pageNo: this.page,
                pageSize: 1000
            };
            this.getCompany()
        //NProgress.start();
            device_group_query(para1).then(res => {
                this.begCode(res.code);
                // this.total = res.data.totalCount;
                this.query = res.data;

                this.querys = [{ id: 0, name: "默认" }];
                this.getrecursion(res.data);
                //NProgress.done();
            });
            if (this.$route.query.id) {
                sessionStorage.setItem('facility_details', this.$route.query.id)
            }
            this.menubt = localStorage.getItem('menubt');
            this.getUser();
            this.t = setInterval(() => {
                let para = {
                    deviceId: sessionStorage.getItem('facility_details')? sessionStorage.getItem('facility_details'):localStorage.getItem('facility_details')
                };
                this.getbodylist();
                device_get(para).then((res) => {
                     this.begCode(res.code,res.message);
                    this.wife = this.formatwife(res.data.deviceAttr)
                    this.facility = res.data;
                    console.log(this.facility)
                    //NProgress.done();
                });
                device_getDeviceAlarmNum(para).then((res) => {
                    //  this.begCode(res.code,res.message);
                    this.AlarmNum = JSON.parse(res.data).alarmNum;
                    console.log(JSON.parse(res.data).alarmNum)

                    //NProgress.done();
                });
            }, 10000)
            let para3 = {
                pagenum:1,
                pageSize: 1000
            }
            unit_query(para3).then((res) => {
                console.log(res)
                this.unitList = res.data.list
            })
        },
        destroyed: function () {
            clearInterval(this.t)
        },
    };
</script>

<style scoped>
    .userlist {
        font-size: 14px;
    }

    #allmap {
        height: 300px;
        overflow: hidden;
        border-radius: 11px;
        overflow: hidden;
    }

    .el-row {
        margin-bottom: 0;
        font-size: 12px;
    }

    .el-col {
        border-radius: 4px;
        margin-bottom: 0px;
    }

    .el-row>.el-col {
        border-radius: 4px;
        margin-bottom: 0;
    }



    .grid-content {
        border-radius: 4px;
        min-height: 36px;
    }

    .row-bg {
        padding: 10px 0;
        background-color: #f9fafc;
    }

    .dev-select {
        width: 100px;
        float: right;
        margin: 3px;
    }

    .dev-title {
        display: inline-block;
        line-height: 36px;
        text-indent: 10px;
        color: #fff
    }

    .device_img {
        /* width: 100%;
        height: auto; */
        /* text-align: center; */
        /* margin-bottom: 15px; */
        /* border: 1px solid #eee; */
        padding: 5px 17px;
    }

    .device_img img {
        width: 267px;
        height: 267px;
        /* max-height: 300px; */
        /* height: 220px; */
        /* width: 100%; */
    }

    .col-bg {
        padding: 12px 15px;
        position: relative;
        height: 100%;
        color: #666666;
        background-color: #ffffff;
        border: none;
        border-radius: 5px;
        border-top-right-radius: 0;
        border-top-left-radius: 0;
        position: relative;
        margin-bottom: 20px;
        box-shadow: 0 5px 5px 0 rgba(0, 0, 0, 0.25);
    }

    .device_p p {
        line-height: 26px;
        margin: 0;
        color: #333;
        font-size: 12px;
    }

    .monitor_data_list2 {
        line-height: 26px;
        padding: 15px 0;
        font-size: 12px;
        color: #000;
        clear: both;
        margin: 10px 0;
        background: #eee;
    }

    .el-table tr {
        position: absolute;
        top: 100px
    }

    .el-table {

        background-color: #eee !important;
    }

    .cell {
        padding-left: 10px !important;
    }

    .ng-binding img {
        vertical-align: baseline;
    }

    .el-col {
        /* min-height: 10px */
        height: 100%;
    }

    .pb-colorbg {
        display: inline-block;
        width: 48px;
        height: 27px; 
        border-radius: 5px;
        line-height: 27px;
        text-align: center;
        font-size: 16px;
        /* width: 20px;
        height: 20px;
        border-radius: 50% */
    }

    .bg-green {
        /* background: green */
        background-color: #D2F5CA;
        color: #4AC936;
        border: 1px solid #4AC936;
    }

    .bg-red {
        background: red;
    }

    .bg-grays {
        /* background: #666; */
        background-color: rgba(220, 222, 234, 0.20);
        border: 1px solid #a9a9ae;
        color: #a9a9ae;
    }
    .controlbtn{
        width: 30%;
        text-align: center;
        padding: 0;
    }
    .name-title{
        display: flex;
        justify-content: space-between;
        align-items: center;
    }
    .device-msg{
        width: 100%;
        margin: 0 auto;
        background-color: #FAFAFA;
        border: 1px solid #E5E5E5;
        /* display: flex; */
        justify-content: space-around;
        border-radius: 11px;
        margin-top: 13px;
        /* padding: 27px; */
    }
    .device-msg-detail{
        display: flex;
        padding: 27px 0;
    }
    .device-msg-image{
        display: inline-block;
        width: 53px;
        height: 53px;
    }
    .device-msg-title{
        color: #B1B1B1;
        font-size: 16px;
    }
    .device-msg-name{
        font-size: 21px;
        color: #07233A;
    }
    .device-msg-name span{
        display: inline-block;
        width: 11px;
        height: 21px;
        border-radius: 3px;
    }
    .bg-greens{
        background: #4AC936;
    }
    .bg-gray{
        background: #DCDEEA;
    }
    .onoffline{
        /* width: 83px;
        height: 32px; */
        width: 62px;
        height: 24px;
        font-size: 14px;
        border: 1px solid;
        border-radius: 16px;
        display: flex;
        justify-content: center;
        align-items: center;
        position: absolute;
        right: 20px;
        top: 10px;
    }
    .onoffline-point{
        display: inline-block;
        width: 11px;
        height: 11px;
        border-radius: 50%;
        background: red;
        margin-right: 4px;
    }
    .devicepoint-title{
        font-size: 16px;
        color: #B1B1B1;
    }
    .devicepoint-content{
        font-size: 19px;
        color: #07233A;
        white-space: nowrap;
        text-overflow: ellipsis;
        overflow: hidden;
    }
    .device-msg-icon{
        width: 16px;
        height: 16px;
    }
    .device-msg-fontsize{
        font-size: 14px
    }
    .flex{
        display:flex;
    }
    .justify-between{
        justify-content:space-between;
    }
    .device-msg-bottomline{
        position: relative;
    }
    .device-msg-bottomline::after{
        content:'';
        display: inline-block;
        width: 100%;
        height: 1px;
        background: #E7EBEE;
        position: absolute;
        bottom: -10px;
        left: 50%;
        transform: translateX(-50%);
    }
    .devicemsg-value{
        color: #A7AAC5;
    }
    .version-msg{
        display: flex;
        font-size: 15px;
    }
    .version-label{
        display: inline-block;
        width: 10%;
        height: 60px;
        border: 1px solid #000;
        line-height: 60px;
        padding-left: 20px;
        color: #6e798c;
    }
    .version-value{
        display: inline-block;
        width: 20%;
        height: 60px;
        border: 1px solid #000;
        line-height: 60px;
        padding-left: 20px;
        color: #A7AAC5;
    }
</style>